import { Context } from 'koa';
import { User } from '../entitys/User';
import { JsonController, Post, BodyParam, Param, Req, Ctx } from "routing-controllers"
import UserService from "../services/UserService"
import Response from '../common/response';
import { strToMd5 } from "../utils/utils"
import AuthService from "../services/AuthService"
import CaptchaService from "../services/CaptchaService"
import { Inject } from "typedi"
import { LoginLogService } from '../services/LoginLogService';

@JsonController()
export default class Login {
    @Inject()
    userService: UserService
    @Inject()
    authService: AuthService
    @Inject()
    captahaService: CaptchaService
    @Inject()
    loginLogService: LoginLogService
    @Post("/login")
    async login(@Ctx() ctx: Context, @BodyParam("username", { required: true }) username: string,
        @BodyParam("password", { required: true }) password: string,
        @BodyParam("codeKey", { required: true }) codeKey: string,
        @BodyParam("code", { required: true }) code: string) {

        let checkType = await this.captahaService.checkSvgCode(codeKey, code)
        if (checkType == 0) {
            return Response.BAD_REQUEST("验证码已失效")
        }
        if (checkType == 1) {
            return Response.BAD_REQUEST("验证码输入错误")
        }
        let user = await this.userService.selectUserByUsername(username)
        if (user && (user.dataStatus >= 0 && user.dataStatus <= 1)) {
            if (user.dataStatus === 0) {
                return Response.BAD_REQUEST("当前用户已经停用")
            }
            if (!this.checkUser(user, password)) {
                return Response.BAD_REQUEST("密码错误")
            }
        } else {
            return Response.BAD_REQUEST("用户不存在")
        }

        delete user.password
        let token = await this.authService.saveUserToRedis(user)
        let data = {
            token,
            userInfo: user
        }
        this.loginLogService.save(ctx, user)
        return Response.SUCCESS(data)
    }
    private checkUser(user: any, password: string) {
        let pwdMd5 = strToMd5(password)
        return user.password === pwdMd5
    }

}
